import { View } from '@tarojs/components';
import {
  hideLoading,
  navigateTo,
  showLoading,
  showToast,
  stopPullDownRefresh,
  useDidShow,
  usePullDownRefresh,
  useReachBottom,
  useRef,
  useState
} from '@tarojs/taro';
import dayjs from 'dayjs';
import Layout from '../../components/Layout';
import Empty from '../../components/Result/Empty';
import XList from '../../components/XList';
import XRow from '../../components/XRow';
import XTab from '../../components/XTab';
import { taskPriObject, taskStatus } from '../../constant/label';
import baseService from '../../utils/baseService';
import './css/index.less';

const Index = () => {
  const [task, setTask] = useState({});
  const [rows, setRows] = useState([]);
  const [users, setUsers] = useState({});
  const pageIndex = useRef(1);
  const productIdRef = useRef(null);
  const tabActiveIndex = useRef(0);
  const tabOptions = ['指给我的', '我完成的', '我创建的'];

  useDidShow(() => {
    getRows();
  });

  usePullDownRefresh(() => {
    pageIndex.current = 1;
    getRows(() => {
      stopPullDownRefresh();
    });
  });

  useReachBottom(() => {
    if (task['pager']['pageTotal'] > pageIndex.current) {
      pageIndex.current++;
      getRows();
    }
  });

  const getRows = (cb = null) => {
    const tps = {
      0: 'assignedTo',
      1: 'finishedBy',
      2: 'openedBy'
    };
    const url =
      '/my-task-' +
      tps[tabActiveIndex.current] +
      '-id_desc--10-' +
      pageIndex.current +
      '.json';
    showLoading({ title: '操作中' });
    baseService
      .query(url, {})
      .then(({ status, data = {} }) => {
        console.log(data);
        const { tasks = [], users = {} } = data;
        setRows(pageIndex.current === 1 ? tasks : rows.concat(tasks));
        setUsers(users);
        setTask(data);
        hideLoading();
        cb && cb();
      })
      .catch(() => {
        showToast({ title: '查询失败', icon: 'none' });
        hideLoading();
      });
  };

  const onChangeTab = (index) => {
    tabActiveIndex.current = index;
    pageIndex.current = 1;
    getRows();
  };

  const onRedirect = (url) => {
    navigateTo({ url });
  };

  return (
    <Layout>
      <View className="issues-icon" onClick={onRedirect.bind(this, 'search')}>
        搜Task
      </View>
      <XTab options={tabOptions} onChange={onChangeTab}></XTab>
      <View>
        {!rows.length && <Empty></Empty>}
        {rows.map((x) => (
          <XList
            arrow="right"
            isCustomize={true}
            key={x.id}
            style={{ padding: '8px 10px 8px 15px', marginBottom: '4px', fontSize: '14px' }}
            onClick={onRedirect.bind(this, 'detail?id=' + x['id'])}
          >
            <XRow>{x['name']}</XRow>
            <XRow style={{ fontSize: '12px', color: '#8c8c8c' }}>
              <XRow>
                <View
                  style={{
                    marginRight: '5px'
                  }}
                >
                  #{x['id']}
                </View>
                <View style={{ color: '#13c2c2', marginRight: '5px' }}>
                  <View
                    style={{
                      color: taskPriObject[x['pri']].color,
                      width: '15px',
                      height: '15px',
                      fontSize: '12px',
                      borderRadius: '50%',
                      border: '2px solid ' + taskPriObject[x['pri']].color,
                      display: 'flex',
                      justifyContent: 'center',
                      alignItems: 'center'
                    }}
                  >
                    {taskPriObject[x['pri']].label}
                  </View>
                </View>
                <View style={{ color: taskStatus[x['status']].color, marginRight: '5px' }}>
                  {taskStatus[x['status']].label}
                </View>
              </XRow>
              最近修改：
              {`${
                x['lastEditedBy']
                  ? users[x['lastEditedBy']] || x['lastEditedBy']
                  : users[x['openedBy']] || x['openedBy']
              } ${
                x['lastEditedBy']
                  ? dayjs(x['lastEditedDate']).format('MM-DD HH:mm')
                  : dayjs(x['openedDate']).format('MM-DD HH:mm')
              }`}
            </XRow>
          </XList>
        ))}
      </View>
    </Layout>
  );
};
Index.config = { navigationBarTitleText: 'Task管理', enablePullDownRefresh: true };
export default Index;
